using System;
using System.Collections;
using System.Collections.Generic;
using TeamTasker.Utils;
using Spring.Context;
using Spring.Context.Support;

namespace TeamTasker.Utils
{
    public class BeanFactory
    {
        protected static BeanFactory instance = null;

        private IApplicationContext springAppCtx = null;

        private BeanFactory()
        {
        }

        public object GetObject(string objectName)
        {
            CheckInitState();
            if (springAppCtx.ContainsObject(objectName))
            {
                return springAppCtx.GetObject(objectName);
            }
            throw new Exception("No such object in configuration: " + objectName);
        }

        public bool ContainsObject(string objectName)
        {
            CheckInitState();
            return springAppCtx.ContainsObject(objectName);
        }

        public IDictionary GetObjectsOfType(Type type)
        {
            CheckInitState();
            if (type == null)
            {
                throw new ArgumentException("Requested type is illegal: null");
            }
            return springAppCtx.GetObjectsOfType(type);
        }

        protected void CheckInitState()
        {
            if (springAppCtx == null)
            {
                throw new Exception("Spring configuration is not initialized");
            }
        }

        public static BeanFactory Instance
        {
            get 
            {
                if (instance == null)
                {
                    throw new Exception("Unable to return bean factory instance: it's not initialized yet");
                }
                return instance;
            }
        }

        public static void Init(string[] configFilePathes)
        {
            if (configFilePathes == null || configFilePathes.Length == 0)
            {
                throw new Exception("Configuration file pathes list is not specified");
            }
            IApplicationContext ctx = new XmlApplicationContext(configFilePathes);
            instance = new BeanFactory();
            instance.springAppCtx = ctx;
        }
    }
}